package org.ytor.core.sysapi.depart.logic;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ytor.common.util.Colls;
import org.ytor.common.util.tree.Trees;
import org.ytor.core.sqlflow.BaseLogic;
import org.ytor.core.sysapi.depart.model.SysDepart;
import org.ytor.core.sysapi.depart.repository.SysDepartRepository;
import org.ytor.core.sysapi.depart.resp.SysDepartResp;
import org.ytor.core.sysapi.dict.service.IDictParse;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * created by yangtong on 2025年6月2日 21:35:23
 * <br/>
 * 部门表
 */
@Service
@RequiredArgsConstructor
public class SysDepartLogic extends BaseLogic<SysDepart, SysDepartRepository> {

    private final IDictParse dictParse;

    public List<Map<String, Object>> tree(String departName) {
        List<SysDepart> list = repository.queryList();
        List<SysDepartResp> sysDepartResps = list.stream().map(SysDepart::toResp).toList();
        List<SysDepartResp> tree = Trees.toTree(sysDepartResps, departName);

        List<Map<String, Object>> departTree = new ArrayList<>();
        for (SysDepartResp sysDepartResp : tree) {
            departTree.add(parseDict(sysDepartResp));
        }
        return departTree;
    }

    private Map<String, Object> parseDict(SysDepartResp resp) {
        Map<String, Object> translatedDepart = dictParse.translate(resp);
        if (Colls.isEmpty(resp.getChildren())) {
            return translatedDepart;
        }
        List<Map<String, Object>> children = new ArrayList<>();
        for (SysDepartResp child : resp.getChildren()) {
            children.add(parseDict(child));
        }
        translatedDepart.put("children", children);
        return translatedDepart;
    }
}